<?php
	check_login();
	$a = getAction();
		
	switch ($a) 
	{
		case "index":
			$url = "admin.php?m=promoter";
			$sql = " select * from " .table('promoter')
				 . " WHERE 1=1 "
				 . " order by id desc";
			
			//分页
			$rscount = $db->getOne("select count(*) from (" . $sql . ") temp");
			$page = max(1, intval($_GET['page']));
			$start = ($page-1) * PAGE_SIZE;
			$pagelist = multipage($rscount, PAGE_SIZE, $page, $url);
			$sql .= " limit $start, " . PAGE_SIZE;
			
			$list = $db->getAll($sql);
			
			for($i = 0; $i < count($list); $i++) {
				$list[$i]["recharge_url"] = "http://" . $_SERVER["HTTP_HOST"] . "/" . $list[$i]["recharge_url"];
				$list[$i]["order_cnt"] = $db->getOne("select * from " . table("order") . " where promoter_id = " . $list[$i]["id"] . " and status = '" . ORDER_STATUS::FINISHED . "'");
			}
			
			$smarty->assign("pagelist", $pagelist);
			$smarty->assign("list", $list);
			$smarty->display("promoter.html");

			break;
		
		case "add":
			$id = get_post("id");
			
			if($_POST) {
				$formData = $_POST["formData"];
				$nowTime = getNowTime();
				
				if (!$formData["name"]) {
					errback("名称不能为空！");
				}
				
				if ($formData["login_id"]) {
					$check = $db->getOne("select count(1) from " . table("promoter") . " where id <> '$id' and login_id = '" . $formData["login_id"] . "'");
					if($check) {
						errback("该用户名已经被别的推广商使用，请输入别的用户名！");
					}
				}
				
				if($id) {
					$formData["id"] = $id;
					$formData["recharge_url"] = "wap.php?m=recharge&promoter=$id";
					$formData["update_time"] = $nowTime;
					$db->update("promoter", $formData, " and id = $id ");
				} else {
					$formData["insert_time"] = $nowTime;
					$formData["update_time"] = $nowTime;
					$id = $db->insert("promoter", $formData);
					
					$formData["recharge_url"] = "wap.php?m=recharge&promoter=$id";
					$db->update("promoter", $formData, " and id = $id ");
				}
				
				gourl("admin.php?m=promoter");
			} else {
				if($id) {
					$formData = $db->getRow("select * from " . table('promoter') . " where id = $id ");
					if($formData["recharge_url"]) {
						$formData["recharge_url"] = "http://" . $_SERVER["HTTP_HOST"] . "/" . $formData["recharge_url"];
					}
					$formData["login_url"] = "http://" . $_SERVER["HTTP_HOST"] . "/cadmin.php";
					$smarty->assign("formData", $formData);
				}
				
				$smarty->display("promoter_add.html");
			}
			
			break;

// 		case "del":
// 			$id = intval($_GET['id']);
// 			$loginId = $db->getOne("select login_id from ".table('admin')." where id='$id' ");
			
// 			if($loginId && $loginId != 'admin') {
// 				$db->query("delete from ".table('admin')." where id='$id' ");
// 			}
// 			gourl();
				
// 			break;
	}

?>

